package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.constant.BompTreeNodeConstant;
import cc.rengu.igas.bomp.common.constant.DubboMethodConstant;
import cc.rengu.igas.bomp.common.dao.AlipayMchntInfoMapper;
import cc.rengu.igas.bomp.common.dao.BizTmpMapper;
import cc.rengu.igas.bomp.common.dao.MchntImageInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.AlipayMchntInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.BizTmpMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntImageInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.AlipayMchntInfo;
import cc.rengu.igas.bomp.common.entity.BizTmp;
import cc.rengu.igas.bomp.common.entity.MchntBaseInfo;
import cc.rengu.igas.bomp.common.entity.MchntImageInfo;
import cc.rengu.igas.bomp.common.enums.ImageTypeEnum;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.common.enums.SysParamEnum;
import cc.rengu.igas.bomp.common.util.ImageHandleUtil;
import cc.rengu.igas.bomp.common.util.InitParamUtil;
import cc.rengu.igas.bomp.core.realize.MchntImageUnifiedService;
import cc.rengu.igas.bomp.core.realize.impl.MchntImageUnifiedServiceImpl;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.enums.BompImageFileOprTypeEnum;
import cc.rengu.igas.bomp.facade.enums.BompImageTypeEnum;
import cc.rengu.igas.bomp.facade.enums.BompImageUploadTypeEnum;
import cc.rengu.igas.bomp.facade.request.ImageFileUpDownloadRequest;
import cc.rengu.igas.bomp.facade.response.ImageFileUpDownloadResponse;
import cc.rengu.igas.channel.alipay.facade.request.ImageUploadRequest;
import cc.rengu.igas.channel.alipay.facade.response.ImageUploadResponse;
import cc.rengu.igas.channel.alipay.facade.result.Result;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/*
 * 图片文件上传下载服务
 * Created by 王成 on 2018/10/23.
 */
public class ImageFileUpDownloadService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        ImageFileUpDownloadRequest imageFileUpDownloadRequest = new ImageFileUpDownloadRequest();
        ConvertUtil.convertOutput(imageFileUpDownloadRequest);
        //临时处理，待前端修改完成后去掉这两行代码
        if (StringUtil.isEmptyOrNull(imageFileUpDownloadRequest.getFileType())) {
            imageFileUpDownloadRequest.setFileType(imageFileUpDownloadRequest.getImageType());
        }

        BompImageFileOprTypeEnum bompImageFileOprTypeEnum = BompImageFileOprTypeEnum.getBompImageFileOprTypeByType(imageFileUpDownloadRequest.getOprType());
        if (null == bompImageFileOprTypeEnum) {
            rglog.error("图片文件上传下载操作类型OprType，不支持的操作类型<{}>!", imageFileUpDownloadRequest.getOprType());
            throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
        }

        BompImageTypeEnum bompImageTypeEnum = BompImageTypeEnum.getImageTypeEnumByImageType(imageFileUpDownloadRequest.getFileType());
        if (null == bompImageTypeEnum) {
            rglog.error("图片类型枚举fileType，不支持的操作类型<{}>!", imageFileUpDownloadRequest.getFileType());
            throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
        }
        return imageFileUpDownloadRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        ImageFileUpDownloadRequest imageFileUpDownloadRequest = (ImageFileUpDownloadRequest) request;
        ImageFileUpDownloadResponse imageFileUpDownloadResponse = new ImageFileUpDownloadResponse();
        imageFileUpDownloadResponse.setHeader(imageFileUpDownloadRequest.getHeader());
        /* 组装应答报文 */
        BizResponse bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(imageFileUpDownloadResponse);
        xmlTreeUtil.deleteXmlTreeNode(BompTreeNodeConstant.IMAGE_DATA);

        /* 获取图片存储根路径 */
        String instId = imageFileUpDownloadRequest.getHeader().getInstId();
        if (BompImageFileOprTypeEnum.UPLOAD.getType().equals(imageFileUpDownloadRequest.getOprType())) {
            /* 图片上传 */
            uploadToServer(imageFileUpDownloadRequest, imageFileUpDownloadResponse);
        } else if (BompImageFileOprTypeEnum.DOWNLOAD.getType().equals(imageFileUpDownloadRequest.getOprType())) {
            /*图片下载*/
            if (BompImageUploadTypeEnum.REAL_NAME_QRCODE.getImageType().equals(imageFileUpDownloadRequest.getFileType())) {
                realNameQrcodeDownload(imageFileUpDownloadRequest, imageFileUpDownloadResponse);
            } else {
                imageFileDownload(imageFileUpDownloadRequest, imageFileUpDownloadResponse);
            }
        } else if (BompImageFileOprTypeEnum.UPLOAD_SERVER_AND_UPLOAD_ALI.getType().equals(imageFileUpDownloadRequest.getOprType())) {
            if (!BompImageUploadTypeEnum.MCHNT_IMAGE.getImageType().equals(imageFileUpDownloadRequest.getFileType())) {
                rglog.error("图片文件上传同时上传支付宝失败，只允许上传类型为商户入驻映像信息图片!fileType:{}", imageFileUpDownloadRequest.getFileType());
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
            if (StringUtil.isEmptyOrNull(imageFileUpDownloadRequest.getMchntNo())) {
                rglog.error("图片文件上传同时上传支付宝失败，商户号为空!");
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
            //上传图片到服务器
            String fullLocalPath = uploadToServer(imageFileUpDownloadRequest, imageFileUpDownloadResponse);
            uploadToAliPay(xmlTreeUtil, imageFileUpDownloadRequest, imageFileUpDownloadResponse, fullLocalPath);
        } else if (BompImageFileOprTypeEnum.UPLOAD_SERVER_AND_UPLOAD_WECHAT.getType().equals(imageFileUpDownloadRequest.getOprType())) {
            if (!BompImageUploadTypeEnum.MCHNT_IMAGE.getImageType().equals(imageFileUpDownloadRequest.getFileType())) {
                rglog.error("图片文件上传同时上传微信失败，该操作只允许上传类型为商户入驻映像信息图片!fileType:{}", imageFileUpDownloadRequest.getFileType());
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
            if (StringUtil.isEmptyOrNull(imageFileUpDownloadRequest.getMchntNo())) {
                rglog.error("图片文件上传同时上传微信失败，商户号为空!");
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
            //上传图片到服务器
            String imageFullLocalPath = uploadToServer(imageFileUpDownloadRequest, imageFileUpDownloadResponse);
            MchntBaseInfo mchntBaseInfo = (MchntBaseInfo) xmlTreeUtil.getXmlTreeObjectValue(BompTreeNodeConstant.MCHNT_BASE_INFO, MchntBaseInfo.class);
            MchntImageUnifiedService mchntImageUnifiedService = new MchntImageUnifiedServiceImpl();
            String mediaId = mchntImageUnifiedService.uploadToWechat(mchntBaseInfo, null, imageFullLocalPath);
            imageFileUpDownloadResponse.setImageId(mediaId);
        } else if (BompImageFileOprTypeEnum.TO_UPLOAD_ALI.getType().equals(imageFileUpDownloadRequest.getOprType())) {
            if (!BompImageUploadTypeEnum.MCHNT_IMAGE.getImageType().equals(imageFileUpDownloadRequest.getFileType())) {
                rglog.error("已有图片文件再上传支付宝失败，该操作只允许上传类型为商户入驻映像信息图片!fileType:{}", imageFileUpDownloadRequest.getImageType());
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
            //根据上送Id查找文件地址
            MchntImageInfoMapper mchntImageInfoMapper = new MchntImageInfoMapperImpl();
            MchntImageInfo imageInfo = mchntImageInfoMapper.selectMchntImageInfoById(instId, imageFileUpDownloadRequest.getId());
            if (null == imageInfo) {
                rglog.error("查询商户映像信息为空！id:{}，mchntNo：{}", imageFileUpDownloadRequest.getId(), imageFileUpDownloadRequest.getMchntNo());
                throw new BizException(RespCodeEnum.RECORD_NOT_FOUND.getRespCode(), RespCodeEnum.RECORD_NOT_FOUND.getRespDesc());
            }
            if (StringUtil.isEmptyOrNull(imageFileUpDownloadRequest.getMchntNo())) {
                rglog.error("图片文件上传同时上传微信失败，商户号为空!");
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
            String downloadFilePath = getFullImageStoragePath(imageFileUpDownloadRequest, imageInfo.getImageLocalPath());
            uploadToAliPay(xmlTreeUtil, imageFileUpDownloadRequest, imageFileUpDownloadResponse, downloadFilePath);
        } else if (BompImageFileOprTypeEnum.TO_UPLOAD_WECHAT.getType().equals(imageFileUpDownloadRequest.getOprType())) {
            if (!BompImageUploadTypeEnum.MCHNT_IMAGE.getImageType().equals(imageFileUpDownloadRequest.getFileType())) {
                rglog.error("已有图片文件再上传微信失败，该操作只允许上传类型为商户入驻映像信息图片!fileType:{}", imageFileUpDownloadRequest.getImageType());
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
            //根据上送Id查找文件地址
            MchntImageInfoMapper mchntImageInfoMapper = new MchntImageInfoMapperImpl();
            MchntImageInfo imageInfo = mchntImageInfoMapper.selectMchntImageInfoById(instId, imageFileUpDownloadRequest.getId());
            if (null == imageInfo) {
                rglog.error("查询商户映像信息为空！id:{}，mchntNo：{}"
                        , imageFileUpDownloadRequest.getId(), imageFileUpDownloadRequest.getMchntNo());
                throw new BizException(RespCodeEnum.RECORD_NOT_FOUND.getRespCode(), RespCodeEnum.RECORD_NOT_FOUND.getRespDesc());
            }
            if (StringUtil.isEmptyOrNull(imageFileUpDownloadRequest.getMchntNo())) {
                rglog.error("图片文件上传同时上传微信失败，商户号为空!");
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
            String downloadFilePath = getFullImageStoragePath(imageFileUpDownloadRequest, imageInfo.getImageLocalPath());
            MchntBaseInfo mchntBaseInfo = (MchntBaseInfo) xmlTreeUtil.getXmlTreeObjectValue(BompTreeNodeConstant.MCHNT_BASE_INFO, MchntBaseInfo.class);
            MchntImageUnifiedService mchntImageUnifiedService = new MchntImageUnifiedServiceImpl();
            String mediaId = mchntImageUnifiedService.uploadToWechat(mchntBaseInfo, null, downloadFilePath);
            imageFileUpDownloadResponse.setImageId(mediaId);
        }

        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        ImageFileUpDownloadResponse imageFileUpDownloadResponse = (ImageFileUpDownloadResponse) bizResponse.getResult();
        ConvertUtil.convertInput(imageFileUpDownloadResponse);
    }

    /*
     * 图片上传
     */
    private String uploadToServer(ImageFileUpDownloadRequest imageFileUpDownloadRequest, ImageFileUpDownloadResponse imageFileUpDownloadResponse) {
        String imageFullLocalPath;
        try {
            if (null == imageFileUpDownloadRequest.getImageData()) {
                rglog.error("文件名<{}>对应的内容不能为空!", imageFileUpDownloadRequest.getImageName());
                throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
            }
            if (StringUtils.isEmpty(imageFileUpDownloadRequest.getMchntNo())
                    && (BompImageUploadTypeEnum.MCHNT_IMAGE.getImageType().equals(imageFileUpDownloadRequest.getFileType())
                    || BompImageUploadTypeEnum.MCHNT_INSPECT.getImageType().equals(imageFileUpDownloadRequest.getFileType())
                    || BompImageUploadTypeEnum.TRANS_VOUCHER.getImageType().equals(imageFileUpDownloadRequest.getFileType())
                    || BompImageUploadTypeEnum.PLAT_MCHNT_LOGO.getImageType().equals(imageFileUpDownloadRequest.getFileType()))) {
                rglog.error("商户入驻、商户巡检、交易凭证以及平台商户LOGO图片类型均需要上传商户号！imagetype:{}", imageFileUpDownloadRequest.getImageType());
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }
            int lastIndex = imageFileUpDownloadRequest.getImageName().lastIndexOf(".");
            if (-1 == lastIndex) {
                rglog.error("文件名<{}>格式不正确.", imageFileUpDownloadRequest.getImageName());
                throw new BizException(RespCodeEnum.IMAGE_NAME_ERROR.getRespCode(), RespCodeEnum.IMAGE_NAME_ERROR.getRespDesc());
            }
            String imageNameSuffix = imageFileUpDownloadRequest.getImageName().substring(lastIndex);
            if (!pattern(imageNameSuffix)) {
                rglog.error("不支持的图片格式:<{}>", imageNameSuffix);
                throw new BizException(RespCodeEnum.IMAGE_NOT_MEET_STANDARD.getRespCode(), RespCodeEnum.IMAGE_NOT_MEET_STANDARD.getRespDesc());
            }
            /* 校验图片大小及像素 */
            byte[] fileBytes = Base64.decodeBase64(imageFileUpDownloadRequest.getImageData());
            if (!checkImage(fileBytes)) {
                rglog.error("上传图片大小及像素不符合系统限制要求，请重新上传!");
                throw new BizException(RespCodeEnum.IMAGE_NOT_MEET_STANDARD.getRespCode(), RespCodeEnum.IMAGE_NOT_MEET_STANDARD.getRespDesc());
            }
            /* 获取文件存储路径参数 */
            String uuid = RandomUtil.getUUID();
            String date = DateUtil.getCurrentDate();
            imageFullLocalPath = getUpImageStoragePath(imageFileUpDownloadRequest, uuid, date);
            /* 将图片保存到本地服务器 */
            rglog.debug("imageFullLocalPath=[{}]", imageFullLocalPath);
            File storageFile = new File(imageFullLocalPath);
            if (!storageFile.exists()) {
                if (!storageFile.getParentFile().exists()) {
                    storageFile.getParentFile().mkdirs();
                }
                storageFile.createNewFile();
            }

            //IO流操作
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(storageFile);
                outputStream.write(fileBytes);
                outputStream.flush();
            } catch (Exception e) {
                rglog.error(e.getMessage());
            } finally {
                //关闭流
                try {
                    if (null != outputStream) {
                        outputStream.close();
                    }
                } catch (Exception e) {
                    rglog.error(e.getMessage());
                }
            }

            if (checkImageFormat(fileBytes)) {
                //图片压缩  大于2M 进行压缩，否则不压缩
                ImageHandleUtil.commpressPicForScale(imageFullLocalPath, imageFullLocalPath, 2048, 0.8);
            }
            BompImageUploadTypeEnum bompImageUploadTypeEnum = BompImageUploadTypeEnum.getBompImageUploadTypeEnumByImageType(imageFileUpDownloadRequest.getFileType());
            //本地地址
            String localPathSuffix = getImageLocalPath(imageFileUpDownloadRequest, getPathByImageType(imageFileUpDownloadRequest, bompImageUploadTypeEnum.getImagePathKey(), ""), uuid, date);
            imageFileUpDownloadResponse.setImageLocalPath(Base64.encodeBase64String(localPathSuffix.getBytes()));
        } catch (BizException e) {
            rglog.error("上传图片异常! exception:{}", e);
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            rglog.error("上传图片异常! exception:{}", e);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        return imageFullLocalPath;
    }

    /*
     * 实名认证商户确认图片下载
     */
    private void realNameQrcodeDownload(ImageFileUpDownloadRequest imageFileUpDownloadRequest, ImageFileUpDownloadResponse imageFileUpDownloadResponse) throws Exception {
        if (StringUtil.isEmptyOrNull(imageFileUpDownloadRequest.getMchntNo())) {
            rglog.error("商户号为空.");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        MchntImageInfoMapper mchntImageInfoMapper = new MchntImageInfoMapperImpl();
        List<MchntImageInfo> mchntImageInfoList = mchntImageInfoMapper.selectMchntImageInfoByMchntNoAndImageType(
                imageFileUpDownloadRequest.getHeader().getInstId(), imageFileUpDownloadRequest.getMchntNo(), ImageTypeEnum.REAL_NAME_QR_CODE.getImageType());
        if (CollectionUtils.isEmpty(mchntImageInfoList)) {
            rglog.error("无实名认证二维码.");
            throw new BizException(RespCodeEnum.IMAGE_NOT_FIND.getRespCode(), RespCodeEnum.IMAGE_NOT_FIND.getRespDesc());
        }
        mchntImageInfoList = mchntImageInfoList.stream().sorted(Comparator.comparing(MchntImageInfo::getImageType)).collect(Collectors.toList());

        SysParam sysParam = SysParamEnum.getSysParam(imageFileUpDownloadRequest.getHeader().getInstId(), SysParamEnum.localStorageRootPath);
        if (null == sysParam) {
            rglog.error("服务器本地图片存储路径未配置.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "服务器本地图片存储路径未配置");
        }
        String filePath = sysParam.getParamValue() + File.pathSeparator + mchntImageInfoList.get(0).getImageLocalPath();
        File downloadFile = new File(filePath);
        if (!downloadFile.exists()) {
            rglog.error("文件<{}>不存在!", filePath);
            throw new BizException(RespCodeEnum.FILE_NOT_EXIST.getRespCode(), RespCodeEnum.FILE_NOT_EXIST.getRespDesc());
        }
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String isGetRequest = xmlTreeUtil.getXmlTreeStringValue(BompTreeNodeConstant.IS_GET_REQUEST);
        if ("Y".equals(isGetRequest)) {
            //get请求下载直接返回
            xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.REAL_IMAGE_PATH, filePath);
            return;
        }

        //IO流操作
        FileInputStream fileInputStream = null;
        byte[] downloadFileBytes = null;
        try {
            fileInputStream = new FileInputStream(downloadFile);
            downloadFileBytes = new byte[fileInputStream.available()];
            fileInputStream.read(downloadFileBytes);
        } catch (Exception e) {
            rglog.error(e.getMessage());
        } finally {
            //关闭流
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            } catch (Exception e) {
                rglog.error(e.getMessage());
            }
        }

        imageFileUpDownloadResponse.setImageData(Base64.encodeBase64String(downloadFileBytes));
        imageFileUpDownloadResponse.setImageLocalPath(Base64.encodeBase64String(mchntImageInfoList.get(0).getImageLocalPath().getBytes()));
    }

    /*
     * 图片下载
     */
    private void imageFileDownload(ImageFileUpDownloadRequest imageFileUpDownloadRequest, ImageFileUpDownloadResponse imageFileUpDownloadResponse) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String localPath = getDownloadPath(imageFileUpDownloadRequest);
        String downloadFilePath = getFullImageStoragePath(imageFileUpDownloadRequest, localPath);
        File downloadFile = new File(downloadFilePath);
        if (!downloadFile.exists()) {
            rglog.error("文件<{}>不存在!", downloadFilePath);
            throw new BizException(RespCodeEnum.FILE_NOT_EXIST.getRespCode(), RespCodeEnum.FILE_NOT_EXIST.getRespDesc());
        }
        String isGetRequest = xmlTreeUtil.getXmlTreeStringValue(BompTreeNodeConstant.IS_GET_REQUEST);
        if ("Y".equals(isGetRequest)) {
            //get请求下载直接返回
            xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.REAL_IMAGE_PATH, downloadFilePath);
            return;
        }

        //IO流操作
        FileInputStream fileInputStream = null;
        byte[] downloadFileBytes = null;
        try {
            fileInputStream = new FileInputStream(downloadFile);
            downloadFileBytes = new byte[fileInputStream.available()];
            fileInputStream.read(downloadFileBytes);
        } catch (Exception e) {
            rglog.error(e.getMessage());
        } finally {
            //关闭流
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            } catch (Exception e) {
                rglog.error(e.getMessage());
            }
        }

        imageFileUpDownloadResponse.setImageData(Base64.encodeBase64String(downloadFileBytes));
        imageFileUpDownloadResponse.setImageLocalPath(Base64.encodeBase64String(localPath.getBytes()));
    }

    private String getDownloadPath(ImageFileUpDownloadRequest request) throws Exception {
        String downloadFilePath;
        String instId = request.getHeader().getInstId();
        String fileType = request.getFileType();
        if (BompImageUploadTypeEnum.MCHNT_IMAGE.getImageType().equals(fileType)) {
            if ("01".equals(request.getHeader().getBizType())) {
                BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
                BizTmp bizTmp = bizTmpMapper.selectBizTmpByRealId(instId, request.getId());
                if (null == bizTmp) {
                    rglog.error("根据ID查询商户映像信息表为空! id：{}", request.getId());
                    throw new BizException(RespCodeEnum.IMAGE_NOT_FIND.getRespCode(), RespCodeEnum.IMAGE_NOT_FIND.getRespDesc());
                }
                String imageJson = InitParamUtil.getJsonString(bizTmp);
                MchntImageInfo mchntImageInfo = JSON.parseObject(imageJson, MchntImageInfo.class);
                downloadFilePath = mchntImageInfo.getImageLocalPath();
            } else {
                MchntImageInfoMapper mchntImageInfoMapper = new MchntImageInfoMapperImpl();
                MchntImageInfo imageInfo = mchntImageInfoMapper.selectMchntImageInfoById(instId, request.getId());
                if (null == imageInfo) {
                    rglog.error("根据ID查询商户映像信息表为空! id：{}", request.getId());
                    throw new BizException(RespCodeEnum.IMAGE_NOT_FIND.getRespCode(), RespCodeEnum.IMAGE_NOT_FIND.getRespDesc());
                }
                downloadFilePath = imageInfo.getImageLocalPath();
            }
        } else if (null != BompImageUploadTypeEnum.getBompImageUploadTypeEnumByImageType(fileType) && !StringUtil.isEmptyOrNull(request.getImageLocalPath())) {
            rglog.info("图片类型：{}", BompImageUploadTypeEnum.getBompImageUploadTypeEnumByImageType(fileType).getDesc());
            downloadFilePath = new String(Base64.decodeBase64(request.getImageLocalPath()));
        } else {
            rglog.error("不允许下载! fileType:{}", fileType);
            throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
        }
        return downloadFilePath;
    }

    private static boolean pattern(String str) {
        /*格式校验*/
        Pattern type = Pattern.compile("\\.doc|\\.docx|\\.xls|\\.xlsx|\\.pdf|\\.jpg|\\.png|\\.jpeg|\\.bmp", Pattern.CASE_INSENSITIVE);
        return type.matcher(str).find();
    }


    /*
     * 根据图片类型获取图片存储服务器路径
     *
     * @param request 业务请求参数
     * @return 图片本地存储路径
     * @throws Exception 异常
     */
    private String getUpImageStoragePath(ImageFileUpDownloadRequest request, String uuid, String date) throws Exception {
        BompImageUploadTypeEnum imageTypeEnum = BompImageUploadTypeEnum.getBompImageUploadTypeEnumByImageType(request.getFileType());
        if (null == imageTypeEnum) {
            rglog.error("图片类型枚举ImageType，不支持的操作类型<{}>!", request.getImageType());
            throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
        }

        String shareUrl = getPathByImageType(request, SysParamEnum.localStorageRootPath.getParamKey(), "");
        shareUrl = getPathByImageType(request, imageTypeEnum.getImagePathKey(), shareUrl);

        return getImageLocalPath(request, shareUrl, uuid, date);
    }

    /*
     * 根据图片类型获取图片存储服务器路径
     *
     * @param request 业务请求参数
     * @return 图片本地存储路径
     * @throws Exception 异常
     */
    private String getFullImageStoragePath(ImageFileUpDownloadRequest request, String localPath) throws Exception {

        BompImageUploadTypeEnum imageTypeEnum = BompImageUploadTypeEnum.getBompImageUploadTypeEnumByImageType(request.getFileType());
        if (null == imageTypeEnum) {
            rglog.error("图片类型枚举ImageType，不支持的操作类型<{}>!", request.getFileType());
            throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
        }

        String shareUrl = getPathByImageType(request, BompAppParamConstant.LOCAL_IMAGE_STORAGE_PATH, "");
        return shareUrl + localPath;
    }

    private String getPathByImageType(ImageFileUpDownloadRequest request, String imagePathKey, String shareUrl) throws Exception {
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(request.getHeader().getInstId(), BompAppParamConstant.IMAGE_STORAGE_PARAM_TYPE, imagePathKey);
        if (null == sysParam) {
            rglog.error("查询系统参数表，根据图片类型获取图片存储服务器路径为空！fileType：<{}>!", request.getFileType());
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }

        if (sysParam.getParamValue().trim().endsWith(File.separator)) {
            shareUrl = shareUrl + sysParam.getParamValue().trim();
        } else {
            shareUrl = shareUrl + sysParam.getParamValue().trim() + File.separator;
        }
        return shareUrl;
    }

    private String getImageLocalPath(ImageFileUpDownloadRequest request, String shareUrl, String uuid, String date) {
        String storagePath;
        int lastIndex = request.getImageName().lastIndexOf(".");
        String imageSuffix = request.getImageName().substring(lastIndex);

        if (BompImageUploadTypeEnum.MCHNT_IMAGE.getImageType().equals(request.getFileType())
                || BompImageUploadTypeEnum.MCHNT_INSPECT.getImageType().equals(request.getFileType())
                || BompImageUploadTypeEnum.TRANS_VOUCHER.getImageType().equals(request.getFileType())
                || BompImageUploadTypeEnum.PLAT_MCHNT_LOGO.getImageType().equals(request.getFileType())) {
            /*  商户影像信息：shareUrl   +   法人行/商户号/上传日期/商户影像文件.jpg */
            /* 巡检           shareUrl   +   法人行/商户号/巡检日期/巡检影像文件.jpg */
            /* 交易凭证       shareUrl   +   法人行/商户号/交易日期/交易凭证文件.jpg*/
            /* 平台商户LOGO：shareUrl   +   法人行/平台商户号/上传日期/平台商户LOGO文件.jpg */
            storagePath = shareUrl + request.getHeader().getInstId() + File.separator
                    + request.getMchntNo() + File.separator + date + File.separator
                    + uuid + imageSuffix;
        } else if (BompImageUploadTypeEnum.CREDIT_REPORT.getImageType().equals(request.getFileType())) {
            /*  征信：   shareUrl +  法人行/查询日期/征信报告.html */
            storagePath = shareUrl + request.getHeader().getInstId() + File.separator
                    + date + File.separator
                    + uuid + imageSuffix;
        } else if (BompImageUploadTypeEnum.QRCODE_LOGO.getImageType().equals(request.getFileType())
                || BompImageUploadTypeEnum.QRCODE_MODE.getImageType().equals(request.getFileType())
                || BompImageUploadTypeEnum.MARKING_ADVERT.getImageType().equals(request.getFileType())
                || BompImageUploadTypeEnum.BANK_LOGO.getImageType().equals(request.getFileType())) {
            //二维码LOGO    shareUrl + 法人行/二维码图片.jpg
            //二维码模板    shareUrl + 法人行/二维码模板.jpg
            //营销广告图片  shareUrl + 法人行/营销广告.jpg
            //银行LOGO     shareUrl + 法人行/银行logo.jpg
            storagePath = shareUrl + request.getHeader().getInstId() + File.separator
                    + uuid + imageSuffix;
        } else if (BompImageUploadTypeEnum.USER_HEAD_IMAGE.getImageType().equals(request.getFileType())) {
            //用户头像  shareUrl +  法人行/系统标识(BSPS或OMPS等)/用户标识/用户影像.jpg
            storagePath = shareUrl + request.getHeader().getInstId() + File.separator
                    + request.getHeader().getSrcSysId() + File.separator
                    + request.getUserId() + File.separator
                    + uuid + imageSuffix;
        } else {
            rglog.error("不支持的上传类型！ImageType：<{}>!", request.getImageType());
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }
        return storagePath;
    }

    /*
     * 校验图片像素及大小
     *
     * @param imageBytesData 图片信息
     * @return true-图片符合要求,false-不符合要求
     * @throws IOException 异常
     */
    protected boolean checkImage(byte[] imageBytesData) throws IOException {
        int size = imageBytesData.length / 1024 / 1024;
        /* 校验图片大小 */
        rglog.info("文件大小<{}>", size);
        if (size > BompAppParamConstant.IMAGE_MAX_SIZE) {
            rglog.info("文件大小<{}>已经超过系统最大限制大小<{}>M", size, BompAppParamConstant.IMAGE_MAX_SIZE);
            return false;
        }

        return true;
    }

    public static boolean checkImageFormat(byte[] iamgeData) {
        if (0x424D == ((iamgeData[0] & 0xff) << 8 | (iamgeData[1] & 0xff))) {
            return true;
        } else if (0x8950 == ((iamgeData[0] & 0xff) << 8 | (iamgeData[1] & 0xff))) {
            return true;
        } else return 0xFFD8 == ((iamgeData[0] & 0xff) << 8 | (iamgeData[1] & 0xff));
    }


    private void uploadToAliPay(XmlTreeUtil xmlTreeUtil, ImageFileUpDownloadRequest imageFileUpDownloadRequest, ImageFileUpDownloadResponse imageFileUpDownloadResponse, String fullLocalPath) throws Exception {
        //获取交易码映射关系
        //上传图片到支付宝
        ImageUploadRequest alipayImageRequest = new ImageUploadRequest();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        String channelSeqNum = sysSeqNum + "1";
        cc.rengu.igas.channel.alipay.facade.base.Header aliHeader = InitParamUtil.initAlipayHeader("imageupload", imageFileUpDownloadRequest.getHeader().getInstId(), channelSeqNum);
        alipayImageRequest.setFilePath(fullLocalPath);
        AlipayMchntInfoMapper alipayMchntInfoMapper = new AlipayMchntInfoMapperImpl();
        AlipayMchntInfo alipayMchntInfo = alipayMchntInfoMapper.selectAlipayMchntInfoByPrimaryKey(imageFileUpDownloadRequest.getHeader().getInstId(), imageFileUpDownloadRequest.getMchntNo());
        if (null == alipayMchntInfo) {
            rglog.error("图片文件上传同时上传微信失败，商户号查询支付宝商户信息表获取费率通道失败!");
            throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
        }
        alipayImageRequest.setChannelId(ChannelEnum.ALIP.getChannelType());

        alipayImageRequest.setChannelType(alipayMchntInfo.getDstChannelType());
        alipayImageRequest.setHeader(aliHeader);
        DubboService dubboService = new DubboServiceImpl();
        Result<ImageUploadResponse> alipayResult = (Result<ImageUploadResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_ALIPAY_PUB_SERVICE, "imageUpload", alipayImageRequest);
        if (null == alipayResult) {
            rglog.error("调用dubbo服务 alipayPubService.imageUpload失败!");
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        } else if (!alipayResult.isSuccess() || !DubboMethodConstant.DUBBO_SUCCESS.equals(alipayResult.getResult().getRespCode())) {
            rglog.error("调用dubbo服务 alipayPubService.imageUpload失败，错误码：<{}>，错误描述：<{}>",
                    alipayResult.getResult().getRespCode(),
                    alipayResult.getResult().getRespDesc());
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), alipayResult.getResult().getRespDesc());
        }

        ImageUploadResponse imageUploadResponse = alipayResult.getResult();
        imageFileUpDownloadResponse.setImageId(imageUploadResponse.getImageId());
    }
}
